package com.huluobo.kotlinim2006a.contract.chat

import android.util.Log
import com.huluobo.kotlinim2006a.adapter.EMCallBackAdapter
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2023/2/8.
 */
class ChatPresenter(private val view: ChatContract.View) : ChatContract.Presenter {
    companion object {
        const val PAGE_SIZE = 10
    }

    val messages = mutableListOf<EMMessage>()

    override fun sendMessage(contact: String, message: String) {
        //构建一条消息
        val emMessage = EMMessage.createTxtSendMessage(message, contact)
        emMessage.setMessageStatusCallback(object : EMCallBackAdapter() {
            override fun onSuccess() {
                runOnUIThread {
                    view.onSendMessageSuccess()
                }
            }

            override fun onError(code: Int, error: String?) {
                runOnUIThread {
                    view.onSendMessageFailed()
                }
                Log.i("TagA", "MessageStatusCallback:$code,error:$error")
            }
        })
        messages.add(emMessage)//往数据源中添加一条消息
        view.onStartSendMessage()
        EMClient.getInstance().chatManager().sendMessage(emMessage)//向服务器中发送消息
    }

    override fun addMessage(userName: String, messages: MutableList<EMMessage>?) {
        //加入当前的消息列表
        messages?.let {
            this.messages.addAll(it)
        }

        //更新消息状态为已读
        val conversation = EMClient.getInstance().chatManager().getConversation(userName)
        conversation.markAllMessagesAsRead()
    }

    override fun loadMessages(userName: String) {
        doAsync {
            val conversation = EMClient.getInstance().chatManager().getConversation(userName)
            conversation.markAllMessagesAsRead()
            messages.addAll(conversation.allMessages)
            runOnUIThread {
                view.onMessageLoaded()
            }
        }
    }

    override fun loadMoreMessage(userName: String) {
        doAsync {
            val conversation = EMClient.getInstance().chatManager().getConversation(userName)
            val startId = messages[0].msgId//查询历史聊天记录的起始位置
            val loadMoreFromDB = conversation.loadMoreMsgFromDB(startId, PAGE_SIZE)
            messages.addAll(0, loadMoreFromDB)//加载历史聊天记录时,不能从list的末尾进行添加,需要从list的头部进行添加
            runOnUIThread {
                view.onMoreMessagesLoaded(loadMoreFromDB.size)
            }
        }
    }
}